package evolution.cli;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import evolution.Directory;
import evolution.File;
import evolution.ResourceException;


public class TransientFile implements File
{
	String content = "";
	private final String name;
	private FileSystemFile delegate;
	private Directory parent;
	private long lastModified;

	public TransientFile(String name, long lastModified)
	{
		this.name = name;
		this.lastModified = lastModified;
	}

	public Reader getReader() throws ResourceException
	{
		if (delegate != null)
		{
			return delegate.getReader();
		}
		else
		{
			return new StringReader(content);
		}
	}

	public Writer getWriter() throws ResourceException
	{
		if (delegate != null)
		{
			return delegate.getWriter();
		}
		else
		{
			return new StringWriter()
			{
				@Override
                public void close()
				{
					content = toString();
				}
			};
		}
	}

	public String getName()
	{
		if (delegate != null)
		{
			return delegate.getName();
		}
		else
		{
			return name;
		}
	}

	public void setParent(Directory parent)
	{
		if (delegate != null)
		{
			delegate.setParent(parent);
		}
		else
		{
			this.parent = parent;
		}
	}

	public String getPath()
	{
		if (delegate != null)
		{
			return delegate.getPath();
		}
		else
		{
			if (parent != null)
			{
				String parentPath = parent.getPath();
				if (parentPath.equals("/"))
				{
					return "/" + getName();
				}
				else
				{
					return parentPath + "/" + getName();
				}
			}
			else
			{
				return getName();
			}
		}
	}

	public void etherealize(FileSystemFile delegate) throws ResourceException
	{
		this.delegate = delegate;
		if (parent != null)
		{
			delegate.setParent(parent);
		}
		Writer writer = delegate.getWriter();
		try
		{
			writer.write(content);
			writer.close();
		}
		catch (IOException e)
		{
			throw new ResourceException("Failed to write content", e);
		}
		content = null;
	}

	@Override
	public String toString()
	{
		return getPath();
	}

	public long getLastModifiedTime()
	{
		return lastModified;
	}

}
